import React, { useEffect, useState } from 'react';
import { FormValueType } from './UpdateForm';
import { TableListItem } from './data';
import { ModalForm } from '@ant-design/pro-form';
import { Tree, Modal } from 'antd';

import {allMenuWithRole} from '../../../Menu/CRUD/service'
import { useImmer } from 'use-immer';

type UpdateMenuFormProps = {
  onCancel: (flag?: boolean, formVals?: FormValueType) => void;
  onSubmit: (values: any) => Promise<void>;
  updateModalVisible: boolean;
  values: Partial<TableListItem>;
};

function generateTree(node: any) {
  if (node.children && node.children.length) {
    return {
      title: node.remark,
      key: node.menuId,
      children: node.children.map((child: any) => generateTree(child)),
    }
  } else {
    return {
      title: node.remark,
      key: node.menuId,
    }
  }
}

const UpdateMenuForm: React.FC<UpdateMenuFormProps & {onVisibleChange: any}> = (props) => {;
  const [treeData, setTreeData] = useImmer<any[]>([])
  const [checkedKeys, setCheckedKeys] = useImmer<React.Key[]>([]);
  useEffect(() => {
    //console.log(props.values)
    allMenuWithRole({roleId: props.values.roleId}).then(res => {
      setCheckedKeys(res?.data.roleHas ?? [])
      setTreeData(res?.data.records.map((item: any) => generateTree(item) ?? []))
    })
  }, [props.values.roleId])
  
  const onCheck = (checkedKeysValue: any, info: any) => {
    setCheckedKeys(checkedKeysValue);
    //console.log('onCheck', checkedKeysValue, info);
  };

  const onSelect = (selectedKeysValue: React.Key[], info: any) => {
    //console.log('onSelect', selectedKeysValue,info);
  };
  

  return (
    <ModalForm
      width={640}
      title="修改菜单"
      open={props.updateModalVisible}
      onFinish={() => props.onSubmit(checkedKeys)}
    >
      <Tree
        checkable
        defaultExpandedKeys={[1]}
        defaultCheckedKeys={[1, 2, 3, 4]}
        checkedKeys={checkedKeys}
        onCheck={onCheck}
        onSelect={onSelect}
        treeData={treeData}
      />
    </ModalForm>
  );
};

export default UpdateMenuForm;
